<?php

namespace App\Console\Commands\Assess;

use App\Models\Assess\ActivateUserManagementEmailModel;
use App\Models\Assess\AutoEmailModel;
use App\Models\Assess\AutoEmailSkuModel;
use App\Models\Assess\EmailTemplateModel;
use App\Models\Assess\SendLogModel;
use App\Models\Register\ActivateUserManagementInfoModel;
use App\Models\Register\ActivateUserManagementModel;
use App\Models\UserModel;
use App\Services\Assess\ActivateService;
use App\Services\Assess\SendLogService;
use App\Services\Common\Ding;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Redis;

class EmailAutoSend extends Command
{
    /**
     *10分钟触发一次自动信
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'email_auto_send
                            {--status=}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '客户激活买家管理,根据步骤发送不同自动信 自动发送';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {

        $ActivateUserManagementModel = new ActivateUserManagementModel();
        $ActivateUserManagementInfoModel = new ActivateUserManagementInfoModel();
        $ActivateService = new ActivateService();
        $AutoEmailModel = new AutoEmailModel();
        $AutoEmailSkuModel = new AutoEmailSkuModel();
        $EmailTemplateModel = new EmailTemplateModel();
        $SendLogModel = new SendLogModel();
        $Ding = new Ding();
        $offset = 0;
        $limit = 20;
        while (true) {
            try {
                $list = $ActivateUserManagementModel
                    ->where('mark', '=', 1) //没有删除
                    ->whereIn('progress_activate', [1,2]) //已经激活和激活异常
                    ->where('alerady_send_auto_email', '=', 0) //没有触发过自动信
                    ->offset($offset)
                    ->limit($limit)
                    ->get(['id', 'progress_activate', 'progress_confirm_gift', 'progress_star_rating_evaluation',
                        'progress_bad_reviews', 'progress_favorable_comment', 'progress_write_address','platform_sku',
                        'customer_confirm_for_review', 'create_user', 'step_end_update_time','evaluate_star_rating',
                        'comment_retention_results','progress_favorable_comment_jump_amazon'])->toArray();

                $offset += $limit;
                if (empty($list)) break;

                $mainTable = $AutoEmailModel->getTable();
                $sonTable = $AutoEmailSkuModel->getTable();
                $emailTemplateTable = $EmailTemplateModel->getTable();

                foreach ($list as $val) {

                    $logCountFailed = $SendLogModel
                        ->where('activate_id','=',$val['id'])
                        ->where('status','=',5)
                        ->where('mark','=',1)
                        ->count();//发送失败尝试5次
                    $logCountNew = $SendLogModel
                        ->where('activate_id','=',$val['id'])
                        ->where('status','=',1)
                        ->where('mark','=',1)
                        ->count(); //已经有待发送了
                    if (!empty($logCountFailed) && $logCountFailed >=5) continue;
                    if (!empty($logCountNew) && $logCountFailed >=1) continue;

//                    if ((time() - $val['step_end_update_time']) <= $endTime) continue;
                    if (!$val['progress_activate']) continue;

                    $redisKey = 'email_auto_send:' . $val['id'] . ':template_type:';
                    $emailData = [
                        'id' => $val['id'],
                        'user_id' => $val['create_user']
                    ];

                    /*
                        发送自动信 匹配规则
                        注册用户-已激活  匹配客户只有激活操作没有后续操作
                        激活异常用户  匹配激活状态是激活异常的
                        中低评分用户  匹配客户给了0~3星 并且没有给评价
                        高评分用户   匹配客户给了3星以上 可以有评价内容也可以没有评价内容
                        选择礼品但未留评用户  匹配客户选择了礼品但没有好评、差评、填写地址信息
                        高评价未匹配用户   匹配客户给了好评论 并且未匹配到在amazon留评
                        高评价已匹配用户  匹配客户给了好评论 并且匹配到在amazon留评
                        系统留评中差评  匹配客户给了差评
                     */

                    ## 不要用elseif 否则顺序会被打乱
                    if ($val['progress_activate']==1) {
                        //判断注册用户-已激活 匹配客户只有激活操作没有后续操作
                        //发送邮件
                        $emailData['template_type'] = EmailTemplateModel::TEMPLATE_TYPE_ACTIVATE;
                        $emailData['source'] = SendLogService::SEND_CLOSE_ACTIVATE;

                    }
                    if ($val['progress_activate']==2) {
                        //激活异常用户 匹配激活状态是激活异常的
                        //发送邮件
                        $emailData['template_type'] = EmailTemplateModel::TEMPLATE_TYPE_ACTIVATE_EXCEPTION;
                        $emailData['source'] = SendLogService::SEND_SOURCE_ACTIVATE_EXCEPTION;

                    }
                    if (!$val['progress_bad_reviews'] && $val['evaluate_star_rating']<=3 && $val['evaluate_star_rating']>0) {
                        //中低评分用户 匹配客户给了0~3星 并且没有给评价
                        //发送邮件
                        $emailData['template_type'] = EmailTemplateModel::TEMPLATE_TYPE_LOW_RATING;
                        $emailData['source'] = SendLogService::SEND_CLOSE_LOW_RATING;
                    }
                    if ($val['evaluate_star_rating']>=3) {
                        //高评分用户 匹配客户给了3星以上 可以有评价内容也可以没有评价内容
                        //发送邮件
                        $emailData['template_type'] = EmailTemplateModel::TEMPLATE_TYPE_HEIGHT_RATING;
                        $emailData['source'] = SendLogService::SEND_CLOSE_HEIGHT_RATING;
                    }
                    if ($val['progress_confirm_gift'] && !$val['progress_bad_reviews'] && !$val['progress_favorable_comment'] &&
                        !$val['progress_write_address']) {
                        //选择礼品但未留评用户-确认礼品 匹配客户选择了礼品但没有好评、差评、填写地址信息
                        //发送邮件
                        $emailData['template_type'] = EmailTemplateModel::TEMPLATE_TYPE_NO_COMMENT;
                        $emailData['source'] = SendLogService::SEND_CLOSE_NO_COMMENT;
                    }

//                    if ($val['progress_favorable_comment'] && !$val['progress_favorable_comment_jump_amazon']) {
//                        //系统留评好评
//                        //发送邮件
//                        $emailData['template_type'] = EmailTemplateModel::TEMPLATE_TYPE_FAVORABLE_COMMENT;
//                        $emailData['source'] = SendLogService::SEND_CLOSE_FAVORABLE_COMMENT;
//                    }
                    if (!empty($val['progress_favorable_comment']) && $val['progress_favorable_comment_jump_amazon'] && !$val['comment_retention_results']) {
                        //高评价未匹配用户  匹配客户给了好评论 并且未匹配到在amazon留评
                        //发送邮件
                        $emailData['template_type'] = EmailTemplateModel::TEMPLATE_TYPE_HEIGHT_RATING_NO;
                        $emailData['source'] = SendLogService::SEND_CLOSE_HEIGHT_RATING_NO;

                    }
                    if (!empty($val['progress_favorable_comment']) && $val['progress_favorable_comment_jump_amazon'] && $val['comment_retention_results'] ) {
                        //高评价已匹配用户  匹配客户给了好评论 并且匹配到在amazon留评
                        //发送邮件
                        $emailData['template_type'] = EmailTemplateModel::TEMPLATE_TYPE_HEIGHT_RATING_YES;
                        $emailData['source'] = SendLogService::SEND_CLOSE_HEIGHT_RATING_YES;

                    }
                    if ($val['progress_bad_reviews'] && !$val['progress_favorable_comment']) {
                        //系统留评中差评 匹配客户给了差评
                        //发送邮件
                        $emailData['template_type'] = EmailTemplateModel::TEMPLATE_TYPE_BAD_REVIEWS;
                        $emailData['source'] = SendLogService::SEND_CLOSE_BAD_REVIEWS;
                    }


                    //读取自动信定时间隔
                    $autoEmailData = $AutoEmailModel::from("$mainTable as m")
                        ->select(['m.id','m.interval_time','email_name'])
                        ->join("$sonTable as s", 's.auto_email_id', '=', 'm.id')
                        ->join("$emailTemplateTable as e", 'm.template_id', '=', 'e.id')
                        ->where('m.create_user','=',$val['create_user'])
                        ->where('m.mark','=',1)
                        ->where('m.status','=',1)
                        ->where('e.type','=',$emailData['template_type'])
                        ->where('s.sku', '=', $val['platform_sku'])->first();

                    $emailData['email_name'] = $autoEmailData['email_name'] ?? '';
//                    if (empty($autoEmailData['interval_time'])) continue;
                    if (empty($autoEmailData)) continue;

                    //如果时间是0 数据超过7分钟没有操作 发送对应自动信
                    if ($autoEmailData['interval_time'] ==0){
                        $diffTime = time() - $val['step_end_update_time'];
                        if ($diffTime < 7*60) continue;
                    }

                    # 如果自动信定时模板没到时间 不触发发送
                    if ( !empty($autoEmailData['interval_time']) && (time() - $val['step_end_update_time']) <= $autoEmailData['interval_time']*60) continue;

                    if (!empty($emailData['template_type'])){
                        //如果存在数据 不进行操作
                        $redisKey .= $emailData['template_type'];
                        if (Redis::get($redisKey)) {
                            continue;
                        }
                        //发送邮件类型 自动任务发送
                        $emailData['send_email_type'] =SendLogService::SEND_EMAIL_TYPE_SYSTEM;

                        $response = $ActivateService->autoSendEmail($emailData);

                        if (!empty($response['code'])) {
                            //记录日志
                            $ActivateUserManagementInfoModel->where('activate_user_id', '=', $val['id'])->update(['send_email_msg' => $response['message']]);
                        } else {
                            $ActivateUserManagementModel->where('id','=',$val['id'])->update(['alerady_send_auto_email'=>1]);

                            //存储并设置过期时间
                            Redis::setex($redisKey, 5 * 60, 1);
                        }
                        $ActivateUserManagementModel->cacheReset($val['id'], [], $val['id']);
                    }
                }

            } catch (\Exception $e) {
                $Ding->text($e->getMessage() . ' ' . $e->getFile() . ' ' . $e->getLine());
            }

        }
    }
}



